/* MDDRIVER.C - test driver for MD2, MD4 and MD5
 */
#include <stdlib.h>
#include <stdio.h>
#include "md5_private.h"
#include "debug.h"


/*
 *Function Name:MDFile
 *
 *Parameters:result should be char[33]
 *
 *Description: Get filename's digest value,the algorithm is confirm
 *				to RFC1321
 *
 *Returns:
 *
 */
void md_file (const char *filename,unsigned char *result)
{

  FILE *file;
  MD5_CTX context;
  int len,i;
  unsigned char buffer[4096]={0},digest[16]={0};
  unsigned char *p=result;


  if ((file = fopen (filename, "rb")) == NULL)
  {
    __ERROR_MSG("I can't open %s,there must \
					be a internal error.\n",filename);
    exit(1);
  }
  else
  {
    MD5Init (&context);
    while ((len = fread (buffer, 1, 1024, file)))
      MD5Update (&context, buffer, len);
    MD5Final (digest, &context);

    fclose (file);
  }

  for (i=0;i<16;i++)
  {
    sprintf((char *)p,"%02x",digest[i]);
    p+=2;
  }

  *p='\0';

  __DEBUG_MSG("File's digest is :%s\n",(char*)result);

  return;
}


void md_buffer(void *buffer, int len, unsigned char *result)
{
  MD5_CTX context;
  int i = 0;
  unsigned char digest[16]={0};
  unsigned char *p=result;

  if (NULL == buffer || NULL == result || len <=0)
  {
    __ERROR_MSG("wrong parameter\n");
    return;
  }

  MD5Init(&context);

  MD5Update(&context, buffer, len);

  MD5Final(digest, &context);

  for (i=0;i<16;i++)
  {
    sprintf((char *)p,"%02x",digest[i]);
    p+=2;
  }

  *p='\0';

  return;
}
